import { exec }  from 'child_process'
const PROCESS_ID = 0; // 要管理的进程ID  
const APP_PATH = './src/signIn/http.js'; // 要启动的应用路径  

// 停止并删除进程  
function stopAndDeleteProcess(id) {
  return new Promise((resolve, reject) => {
    exec(`pm2 stop ${id} && pm2 delete ${id}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`停止和删除进程 ${id} 时出错:`, error);
        reject(error);
      } else {
        console.log(`进程 ${id} 已成功停止和删除。`);
        resolve();
      }
    });
  })
}

// 启动进程  
function startProcess(path) {
  return new Promise((resolve, reject) => {
    exec(`pm2 start ${path}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`启动进程时出错:`, error);
        reject(error);
      } else {
        console.log(`新进程已成功启动。`);
        resolve();
      }
    });
  })
}

// 主逻辑  
export async function managePm2(PROCESS_ID,APP_PATH) {
  try {
    // 尝试停止并删除进程  
    await stopAndDeleteProcess(PROCESS_ID);
    // 启动新进程  
    await startProcess(APP_PATH);
  } catch (error) {
    console.error('管理PM2进程时发生错误:', error);
  }
}

